import {Form, Card, Space, Button, Select, Input, List, Tag, message} from 'antd';
import React, {useState, useEffect} from 'react';
import {PlusOutlined, MinusCircleOutlined, SearchOutlined, UserOutlined, ExclamationCircleOutlined, CheckCircleOutlined} from '@ant-design/icons';
import {namespaceEnvironments} from '@/services/env/api';
import {userPermissionsList} from '@/services/switch/api';
import {useModel} from '@@/exports';

export type ApproverConfigProps = {};

const ApproverConfig: React.FC<ApproverConfigProps> = () => {
  const [envOptions, setEnvOptions] = useState<{label: string, value: number}[]>([]);
  const [searchTexts, setSearchTexts] = useState<{[key: number]: string}>({});
  const [availableApprovers, setAvailableApprovers] = useState<API.UserPermissionsListItem[]>([]);
  const [loadingUsers, setLoadingUsers] = useState<boolean>(false);
  const {initialState} = useModel('@@initialState');
  const {currentUser} = initialState || {};

  // 获取环境列表
  useEffect(() => {
    const fetchEnvironments = async () => {
      console.log('ApproverConfig - 开始获取环境列表, currentUser:', currentUser);
      console.log('ApproverConfig - select_namespace:', (currentUser as any)?.select_namespace);

      if ((currentUser as any)?.select_namespace) {
        try {
          const response = await namespaceEnvironments((currentUser as any).select_namespace);
          console.log('ApproverConfig - API响应:', response);

          if (response?.data) {
            const options = response.data.map((env: API.EnvItem) => ({
              label: env.name,
              value: env.id
            }));
            console.log('ApproverConfig - 处理后的选项:', options);
            setEnvOptions(options);
          } else {
            console.log('ApproverConfig - 响应数据为空');
          }
        } catch (error) {
          console.error('ApproverConfig - 获取环境列表失败:', error);
        }
      } else {
        console.log('ApproverConfig - 没有选择的命名空间');
      }
    };

    if (currentUser) {
      fetchEnvironments();
    }
  }, [currentUser, (currentUser as any)?.select_namespace]);

  // 获取用户列表
  useEffect(() => {
    const fetchUsers = async () => {
      setLoadingUsers(true);
      try {
        const response = await userPermissionsList({
          username: ''
        });
        console.log('ApproverConfig - 用户列表响应:', response);
        if (Array.isArray(response)) {
          setAvailableApprovers(response);
        } else if (response) {
          setAvailableApprovers([]);
        }
      } catch (error) {
        console.error('ApproverConfig - 获取用户列表失败:', error);
      } finally {
        setLoadingUsers(false);
      }
    };

    fetchUsers();
  }, []);

  // 获取特定环境的过滤审批人
  const getFilteredApprovers = (fieldKey: number) => {
    const searchText = searchTexts[fieldKey] || '';
    return availableApprovers.filter(approver =>
      approver.userInfo.username.toLowerCase().includes(searchText.toLowerCase())
    );
  };

  // 更新特定环境的搜索文本
  const updateSearchText = (fieldKey: number, value: string) => {
    setSearchTexts(prev => ({
      ...prev,
      [fieldKey]: value
    }));
  };

  // 检查用户是否有审批权限
  const hasApprovalPermission = (approver: API.UserPermissionsListItem) => {
    return approver.userPermissions && approver.userPermissions.some(permission =>
      permission.name === 'approvals:judge'
    );
  };

  // 添加审批人到表单
  const addApprover = (form: any, fieldName: number, fieldKey: number, approverId: number) => {
    const approver = availableApprovers.find(a => a.userInfo.id === approverId);
    if (!approver) return;

    if (!hasApprovalPermission(approver)) {
      message.warning(`用户 ${approver.userInfo.username} 没有审批权限 (approvals:judge)，无法添加为审批人`);
      return;
    }

    const currentApprovers = form.getFieldValue(['createSwitchApproversReq', fieldName, 'approverUsers']) || [];
    if (!currentApprovers.includes(approverId)) {
      form.setFieldValue(['createSwitchApproversReq', fieldName, 'approverUsers'], [...currentApprovers, approverId]);
    }
    updateSearchText(fieldKey, '');
  };

  // 移除审批人
  const removeApprover = (form: any, fieldName: number, approverId: number) => {
    const currentApprovers = form.getFieldValue(['createSwitchApproversReq', fieldName, 'approverUsers']) || [];
    form.setFieldValue(['createSwitchApproversReq', fieldName, 'approverUsers'],
      currentApprovers.filter((id: number) => id !== approverId)
    );
  };

  // 清理搜索文本状态
  const cleanupSearchText = (fieldKey: number) => {
    setSearchTexts(prev => {
      const newState = { ...prev };
      delete newState[fieldKey];
      return newState;
    });
  };

  return (
    <Card
      title="审批人配置"
      size="small"
      style={{ marginTop: '20px', marginBottom: '60px' }}
    >
      <Form.List name="createSwitchApproversReq" key={`form-list-${envOptions.length}`}>
        {(fields, { add, remove }) => (
          <>
            {fields.map(({ key, name, ...restField }) => (
              <Space key={key} style={{ display: 'block', marginBottom: 24, padding: 16, border: '1px solid #f0f0f0', borderRadius: 6 }} align="baseline">
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
                  <Form.Item
                    {...restField}
                    name={[name, 'envId']}
                    rules={[{ required: true, message: '请选择环境' }]}
                    style={{ marginBottom: 0, marginRight: 16 }}
                  >
                    <Select
                      placeholder="选择环境"
                      style={{ width: 200 }}
                      options={envOptions}
                      showSearch
                      allowClear
                      filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                      }
                      notFoundContent={envOptions.length === 0 ? "正在加载环境数据..." : "暂无环境数据"}
                    />
                  </Form.Item>
                  <Button
                    type="text"
                    danger
                    icon={<MinusCircleOutlined />}
                    onClick={() => {
                      cleanupSearchText(key);
                      remove(name);
                    }}
                  >
                    删除审批
                  </Button>
                </div>

                <div>
                  <div style={{ marginBottom: 12 }}>
                    <Input
                      placeholder="搜索审批人"
                      prefix={<SearchOutlined />}
                      value={searchTexts[key] || ''}
                      onChange={(e) => updateSearchText(key, e.target.value)}
                      style={{ width: '100%' }}
                    />
                  </div>

                  <Form.Item noStyle shouldUpdate>
                    {(form) => {
                      const currentSearchText = searchTexts[key] || '';
                      const filteredApprovers = getFilteredApprovers(key);
                      
                      return (
                        <>
                          {currentSearchText && (
                            <div style={{ marginBottom: 16, maxHeight: 200, overflowY: 'auto', border: '1px solid #f0f0f0', borderRadius: 4 }}>
                              <List
                                size="small"
                                dataSource={filteredApprovers}
                                renderItem={(approver: API.UserPermissionsListItem) => {
                                  const canApprove = hasApprovalPermission(approver);
                                  return (
                                    <List.Item
                                      style={{
                                        cursor: canApprove ? 'pointer' : 'not-allowed',
                                        padding: '8px 12px',
                                        opacity: canApprove ? 1 : 0.6,
                                        backgroundColor: canApprove ? 'transparent' : '#f5f5f5'
                                      }}
                                      onClick={() => addApprover(form, name, key, approver.userInfo.id)}
                                      onMouseEnter={(e) => {
                                        if (canApprove) {
                                          e.currentTarget.style.backgroundColor = '#f5f5f5';
                                        }
                                      }}
                                      onMouseLeave={(e) => {
                                        if (canApprove) {
                                          e.currentTarget.style.backgroundColor = 'transparent';
                                        } else {
                                          e.currentTarget.style.backgroundColor = '#f5f5f5';
                                        }
                                      }}
                                    >
                                      <List.Item.Meta
                                        avatar={
                                          canApprove ?
                                            <CheckCircleOutlined style={{ color: '#52c41a' }} /> :
                                            <ExclamationCircleOutlined style={{ color: '#faad14' }} />
                                        }
                                        title={
                                          <span style={{ color: canApprove ? '#000' : '#999' }}>
                                            {approver.userInfo.username}
                                            {!canApprove && <span style={{ color: '#ff4d4f', marginLeft: 8 }}>(无审批权限)</span>}
                                          </span>
                                        }
                                        description={
                                          <span style={{ color: canApprove ? '#666' : '#999' }}>
                                            用户ID: {approver.userInfo.id} | 权限: { canApprove ? '可以审批' : '无权限'}
                                            {!canApprove && <div style={{ color: '#ff4d4f', marginTop: 4 }}>缺少 "approvals:judge" 权限，无法添加为审批人</div>}
                                          </span>
                                        }
                                      />
                                    </List.Item>
                                  );
                                }}
                              />
                            </div>
                          )}
                        </>
                      );
                    }}
                  </Form.Item>

                  <Form.Item
                    {...restField}
                    name={[name, 'approverUsers']}
                    rules={[{ required: true, message: '请选择审批人' }]}
                  >
                    <Form.Item noStyle shouldUpdate>
                      {(form) => {
                        const selectedApprovers = form.getFieldValue(['createSwitchApproversReq', name, 'approverUsers']) || [];
                        const selectedApproverData = availableApprovers.filter(approver =>
                          selectedApprovers.includes(approver.userInfo.id)
                        );

                        return (
                          <div>
                            <div style={{ marginBottom: 8, fontWeight: 500 }}>已选择的审批人：</div>
                            {selectedApproverData.length === 0 ? (
                              <div style={{ color: '#999', fontStyle: 'italic' }}>暂未选择审批人</div>
                            ) : (
                              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                                {selectedApproverData.map(approver => (
                                  <Tag
                                    key={approver.userInfo.id}
                                    closable
                                    onClose={() => removeApprover(form, name, approver.userInfo.id)}
                                    style={{ marginBottom: 4 }}
                                  >
                                    <UserOutlined style={{ marginRight: 4 }} />
                                    {approver.userInfo.username} ({approver.userPermissions && approver.userPermissions.length > 0 ? '可以审批' : '无权限'})
                                  </Tag>
                                ))}
                              </div>
                            )}
                          </div>
                        );
                      }}
                    </Form.Item>
                  </Form.Item>
                </div>
              </Space>
            ))}
            <Form.Item>
              <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                添加审批环境
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
    </Card>
  );
};

export default ApproverConfig;
